var http=require('http');
var fs=require('fs');
var url=require('url');
var queryString=require('querystring');

function startServer(route,handle){
    //抽象一个方法
    var onRequest=function(request,response){
        
        var pathname=url.parse(request.url).pathname;
        console.log('request received....'+pathname);

        //GET提交解析
        var data=[];
        request.on("error",function(err){
            console.error (err);
        }).on("data",function(chunk){
            data.push(chunk);
        }).on("end",function(){
            if(request.method==='POST'){
                //防止数据过载
                if(data.length>1e6){
                    request.connection.destroy();
                }
                data=Buffer.concat(data).toString();
                route(handle,pathname,response,queryString.parse(data));
            }else{
                //POST提交解析
                var parms=url.parse(request.url,true).query;  //此处true表示按json解析，false为txt解析
                route(handle,pathname,response,parms);
            }            
        });
       
    }
    
    var server=http.createServer(onRequest)

    server.listen(3000,'127.0.0.1');
    console.log('server started on localhost port 3000'); 
}

exports.startServer=startServer;
